package com.zretc.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.zretc.dao.CommentDao;
import com.zretc.entity.Account;
import com.zretc.entity.Comment;
import com.zretc.util.DBUtil;
import com.zretc.util.PageInfo;

/**
 * 评论页面dao层实现类
 * @author Administrator
 *
 */

public class CommentDaoImpl implements CommentDao{
	/**
	 * 插入一条评论
	 * @author hexiawei
	 * return int
	 */
	@Override
	public int insertComent(Comment comment) {
		int n = DBUtil.doUpdate("insert into comment values(?,?,?,?,?)", comment.getCommentId(),comment.getCommentContent(),comment.getAccount().getAccountId(),comment.getSongId(),comment.getCommentTime());
		return n;
	}

	@Override
	public PageInfo<Comment> findCommentBySongId(Map<String, String> map) {
		List<Comment> list = new ArrayList<Comment>();
		Comment comment = null;
		Account account = null;
		String songId = map.get("songId");
		Integer pageNum = Integer.valueOf(map.get("pageNum"));
		Integer pageSize = Integer.valueOf(map.get("pageSize"));
		PageInfo<Comment> pageInfo = null;
		ResultSet rs = DBUtil.doQuery("select A.comment_id,A.comment_content,B.account_id,B.account_tel,B.account_picture,B.vip_status,A.song_id,A.comment_time "
				+ " from comment A left join account B on A.account_id = B.account_id where A.song_id = ? order by A.comment_time desc limit ?,? ", songId,(pageNum-1)*pageSize,pageSize);
		try {
			while (rs.next()) {
				int commentId = rs.getInt("comment_id");
				String commentContent = rs.getString("comment_content");
				int accountId = rs.getInt("account_id");
				String accountTel = rs.getString("account_tel");
				String accountPicture = rs.getString("account_picture");
				int vipStatus = rs.getInt("vip_status");
				String commentTime = rs.getString("comment_time");
				account = new Account(accountId, accountTel, null, vipStatus, accountPicture);
				comment = new Comment(commentId, commentContent, commentTime, account, Integer.parseInt(songId));
				list.add(comment);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		Integer total = 0;
		rs = DBUtil.doQuery("select count(*),A.comment_id,A.comment_content,B.account_id,B.account_tel,B.account_picture,B.vip_status,A.song_id,A.comment_time "
				+ " from comment A left join account B on A.account_id = B.account_id where A.song_id = ?", songId);
		try {
			while (rs.next()) {
				total = rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		pageInfo = new PageInfo<>(list, pageNum, pageSize, total);
		
		return pageInfo;
	}
	
}
